import shutil
import os
from docx import Document
import sqlite3

def modify_docx_copy(docx_path, gen_path, db_path, project_id):
    docx_path = docx_path.replace("\\", "\\\\")
    gen_path = gen_path.replace("\\", "\\\\")
    # 复制原始文件到目标路径，保留原始文件的所有属性
    shutil.copy(docx_path, gen_path)

    # 打开复制后的文档
    doc = Document(gen_path)

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # 遍历文档中的每个段落
    for paragraph in doc.paragraphs:
        # 查找段落中“：”的位置
        colon_index = paragraph.text.find("：")
        if colon_index != -1:
            # 提取“：”之前的内容
            content_before_colon = paragraph.text[:colon_index].strip()
            if content_before_colon == "项目名称":
                sql_select = "select project_name from doctest where project_id = ?;"
                cursor.execute(sql_select, (project_id,))
                results = cursor.fetchall()
                insert_content = results[0][0] if results else ""
            elif content_before_colon == "开始时间":
                sql_select = f"select start_time from doctest where project_id = ?;"
                cursor.execute(sql_select, (project_id,))
                results = cursor.fetchall()
                insert_content = results[0][0] if results else ""
            elif content_before_colon == "主要内容":
                sql_select = f"select addition from doctest where project_id = ?;"
                cursor.execute(sql_select, (project_id,))
                results = cursor.fetchall()
                if len(results) != 0:
                    insert_content = results[0][0] if results else ""
                else:
                    insert_content = ""
            elif content_before_colon == "参与人员":
                sql_select = f"select user_name from project_user where project_id = ?;"
                cursor.execute(sql_select, (project_id,))
                results = cursor.fetchall()
                insert_content = "，".join([result[0] for result in results]) if results else ""


            # 在“：”后面添加前面的内容
            # 遍历段落中的 runs，找到“：”所在的 run
            for run in paragraph.runs:
                if "：" in run.text:
                    # 找到“：”的位置
                    run_text = run.text
                    colon_index_in_run = run_text.find("：")
                    # 在“：”后面添加内容
                    run.text = run_text[:colon_index_in_run + 1] + insert_content + run_text[colon_index_in_run + 1:]
                    break  # 找到后退出循环

    cursor.close()
    conn.close()
    # 保存修改后的文档
    doc.save(gen_path)


# 示例用法
docx_path = os.path.join(os.getcwd(), "test.docx")  # 替换为你的 docx 文件路径
gen_path = os.path.join(os.getcwd(), "test_gen.docx")
db_path = os.path.join(os.getcwd(), "test.db")
modify_docx_copy(docx_path, gen_path, db_path, "000001")
print(f"修改后的文档已保存到 {gen_path}")